#import "LoginUI.h"
#import "JSON.h"
#import "Tools.h"
#import "AppDelegate.h"
#import "MBProgressHUD.h"
#import "ConfigData.h"
@implementation LoginUI
@synthesize flag,code,dic;
//- (BOOL)prefersStatusBarHidden
//{
//    return YES;//隐藏为YES，显示为NO
//}

- (id)init
{
    self = [super init];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cancelLoginFn) name:@"closeActivityLoginFn" object:nil];
    fastLoginButArr = nil;
    fastLoginButArr = [[NSMutableArray alloc] initWithCapacity:0];
    isAutoLogin = NO;
    isRemenberMin = NO;
    return self;
}
-(void) viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}
//用户注册
-(void)regFn{
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"reg" object:nil];
}
-(void)resignKeyboard{
    [userNameField resignFirstResponder];
    [userMinField resignFirstResponder];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor whiteColor];
    
    int h=[Tools getScreenHeight];
    UIView* tmp=[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, h)];
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(resignKeyboard)];
    [tmp addGestureRecognizer:singleTap];
    [self.view addSubview:tmp];
    
    
    UIImage *headImg=[UIImage imageNamed:@"navigation@2x"];
    headImg=[Tools resizeImageToSize:headImg toSize:CGSizeMake(320, 44)];
    
    
    UILabel* titleLb=[[UILabel alloc] initWithFrame:CGRectMake(100, 0, 120, 44)];
    titleLb.text=@"登录";
    titleLb.font=[UIFont systemFontOfSize:HEAD_SIZE];
    titleLb.backgroundColor=[UIColor clearColor];
    titleLb.textAlignment=NSTextAlignmentCenter;
    titleLb.textColor=[UIColor whiteColor];
    self.navigationItem.titleView=titleLb;
    
    
    UIButton* cancelBtn= [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 44)];
    [cancelBtn addTarget:self action:@selector(clickOnBackBut) forControlEvents:UIControlEventTouchUpInside];
    CGRect frame_1= CGRectMake(0,12, 20,20);
    UIImageView*  backView=[[UIImageView alloc] initWithFrame:frame_1];
    UIImage* image= [UIImage imageNamed:@"back2016"];
    backView.image=image;
    [cancelBtn addSubview:backView];
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc] initWithCustomView:cancelBtn];
    
    
    
    
    
    
    
    UIImageView * userNameView = [[UIImageView alloc] initWithFrame:CGRectMake((320-554/2)/2, 10.0+44.0, 554/2, 61/2)];
    userNameView.image = [UIImage imageNamed:@"password2016"];
    userNameView.userInteractionEnabled = YES;
    [self.view addSubview:userNameView];
    
    
    userNameField = [[UITextField alloc] initWithFrame:CGRectMake(50, 0, 554/2-50, 61/2)];
    userNameField.placeholder = @"请输入手机号码";
    
    userNameField.delegate = self;
    userNameField.tag = 9;
    userNameField.keyboardType = UIKeyboardTypeNumberPad;
    userNameField.font=[UIFont systemFontOfSize:14];
    [userNameView addSubview:userNameField];
    
    
    UIImageView * userMinView = [[UIImageView alloc] initWithFrame:CGRectMake((320-554/2)/2, 100.0+30, 554/2, 61/2)];
    userMinView.image = [UIImage imageNamed:@"password2016"];
    userMinView.userInteractionEnabled = YES;
    [self.view addSubview:userMinView];
    
    
    userMinField = [[UITextField alloc] initWithFrame:CGRectMake(50, 0, 554/2-50, 61/2)];
    userMinField.placeholder = @"请输入密码";
    
    userMinField.clearButtonMode = UITextFieldViewModeWhileEditing;
    userMinField.tag = 10;
    userMinField.font=[UIFont systemFontOfSize:14];
    userMinField.autocapitalizationType = UITextAutocapitalizationTypeNone;
    userMinField.delegate = self;
    userMinField.secureTextEntry = YES;
    [userMinView addSubview:userMinField];
    
    
    
    UIButton * loginBtn = [[UIButton alloc] initWithFrame:CGRectMake((320-554/2)/2, 166.0+30, 554/2, 61/2)];
    loginBtn.backgroundColor=[UIColor redColor];
    [loginBtn addTarget:self action:@selector(loginFn) forControlEvents:UIControlEventTouchUpInside];
    
    
    [self.view addSubview:loginBtn];
    //
    UILabel*  loginLb=[[UILabel  alloc] initWithFrame:CGRectMake(0, 0, 554/2, 61/2)];
    loginLb.textColor=[UIColor whiteColor];
    loginLb.text=@"立即登录";
    loginLb.textAlignment=NSTextAlignmentCenter;
    loginLb.font=[UIFont systemFontOfSize:15];
    [loginBtn addSubview:loginLb];
    
    
    
    //
    UIButton*  remberPwdBtn=[[UIButton alloc] initWithFrame:CGRectMake(70, 166.0+30+40, 60, 20)];
    [self.view addSubview:remberPwdBtn];
    UILabel*  remberPwdLb=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 60, 20)];
    remberPwdLb.text=@"记住密码";
    remberPwdLb.textColor=[UIColor redColor];
    remberPwdLb.font=[UIFont systemFontOfSize:13];
    [remberPwdBtn addSubview:remberPwdLb];
    
    //
    
    UIButton*  forgetPwdBtn=[[UIButton alloc] initWithFrame:CGRectMake(200+30, 166.0+30+40, 80, 20)];
    [self.view addSubview:forgetPwdBtn];
    UILabel*  forgetPwdLb=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 80, 20)];
    forgetPwdLb.text=@"忘记密码?";
    forgetPwdLb.textColor=[UIColor redColor];
    forgetPwdLb.font=[UIFont systemFontOfSize:13];
    [forgetPwdBtn addSubview:forgetPwdLb];
    
    
    UIButton*  regBtn=[[UIButton alloc] initWithFrame:CGRectMake(50, h-100, 220, 25)];
    [self.view addSubview:regBtn];
    UILabel* dontRegLb=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 160, 25)];
    dontRegLb.text=@"还没有注册夜店中国账号?";
    dontRegLb.font=[UIFont systemFontOfSize:13];
    dontRegLb.textColor=[UIColor blackColor];
    [regBtn addSubview:dontRegLb];
    //
    UILabel* lijiRegLb=[[UILabel alloc] initWithFrame:CGRectMake(160, 0, 60, 25)];
    lijiRegLb.text=@"立即注册";
    lijiRegLb.font=[UIFont systemFontOfSize:13];
    lijiRegLb.textColor=[UIColor redColor];
    [regBtn addSubview:lijiRegLb];
    
    
}


//取消登录
-(void)clickOnBackBut{
    [self.navigationController popViewControllerAnimated:NO];
}

-(void)loginFn{
    
    NSString * u = ((UILabel *)[self.view viewWithTag:9]).text;
    NSString * p = ((UILabel *)[self.view viewWithTag:10]).text;
    NSLog(@"u=%@,p=%@",u,p);
    
    if ([u isEqualToString:@""]||[p isEqualToString:@""]) {
        
        UIAlertView * myalert = [[UIAlertView alloc] initWithTitle:@"信息提示:" message:@"请先注册或是输入帐户密码再登陆！" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [myalert show];
        
        return;
    }
    else{
        AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
        [[MBProgressHUD showHUDAddedTo:app.window animated:YES] setLabelText:@"加载中,请稍后..."];
        
        [NSThread detachNewThreadSelector:@selector(doLogin) toTarget:self withObject:nil];
    }
}
-(void)doLogin{
    NSString* loginURL=HOST;
    loginURL=[loginURL stringByAppendingString:@"/index.php/appUser/login"];
    NSURL* url=[[NSURL alloc] initWithString:loginURL];
    ASIFormDataRequest *req=[ASIFormDataRequest requestWithURL:url];
    NSString * u = ((UILabel *)[self.view viewWithTag:9]).text;
    NSString * p = ((UILabel *)[self.view viewWithTag:10]).text;
    
    [req addPostValue:u forKey:@"mp"];
    [req addPostValue:p forKey:@"pwd"];
    [req startSynchronous];
    NSError *error = [req error];
    if (!error) {
        AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
        [MBProgressHUD hideHUDForView:app.window animated:YES];
        NSString *response = [req responseString];
        NSLog(@"返回结果..%@",response);
        
        self.dic=[NSMutableDictionary dictionaryWithDictionary:[response JSONValue]];
        NSLog(@"登录失败..%@",dic);
        NSString* _code=[self.dic objectForKey:@"code"];
        self.code=[_code intValue];
        [self performSelectorOnMainThread:@selector(closeLoginPage) withObject:nil waitUntilDone:YES];
    }
    
}
-(void)closeLoginPage{
    if(self.code==7){//用户名或密码失败
        NSLog(@"登录失败..");
        UIAlertView * successTip = [[UIAlertView alloc] initWithTitle:@"信息提示:" message:@"用户名或密码错误，请重现登录！" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [successTip show];
        
    }
    if(self.code==1){//登录成功
        NSString * u = ((UILabel *)[self.view viewWithTag:9]).text;
        NSString *uidStr=[self.dic objectForKey:@"uid"];
        NSLog(@"登录返回结果=%@",dic);
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setValue:uidStr forKey:@"uid"];
        [userDefaults setValue:u forKey:@"u"];
        [userDefaults setValue:userNameField.text forKey:@"mp"];
        UIAlertView * successTip = [[UIAlertView alloc] initWithTitle:@"信息提示:" message:@"登录成功！" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [successTip show];
        
        
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshMoreFn" object:nil];
        [self.navigationController popViewControllerAnimated:NO];
        
        
    }
    
}


//记住密码
-(void)userClickOnRemenberMinBut{
    
    if (!isRemenberMin) {
        ((UIImageView *)[self.view viewWithTag:99]).image = [UIImage imageNamed:@"niming1.png"];
    }
    else{
        ((UIImageView *)[self.view viewWithTag:99]).image = [UIImage imageNamed:@"niming.png"];
    }
    isRemenberMin = !isRemenberMin;
    
}

//自动登陆
-(void)userClickOnAutoLogin{
    
    if (!isAutoLogin) {
        ((UIImageView *)[self.view viewWithTag:100]).image = [UIImage imageNamed:@"niming1.png"];
        //自动登陆
        [[NSUserDefaults standardUserDefaults]setObject:@"isisAutoLogin" forKey:@"isAutoLogin"];
    }
    else{
        
        ((UIImageView *)[self.view viewWithTag:100]).image = [UIImage imageNamed:@"niming.png"];
        //不自动登陆
        [[NSUserDefaults standardUserDefaults]setObject:@"" forKey:@"isAutoLogin"];
    }
    isAutoLogin = !isAutoLogin;
    
    
}

-(void)userClickOnRegisterBut{
    //    [[NSNotificationCenter defaultCenter] postNotificationName:@"backtohome" object:nil];
    //
    //    [[NSNotificationCenter defaultCenter] postNotificationName:@"regFn" object:nil];
    
    
    
    //[self dismissModalViewControllerAnimated:NO];
    
    
    //    RegVC* reg=[[RegVC alloc] init];
    //    UINavigationController *nav=[[UINavigationController alloc] initWithRootViewController:reg];
    //    [self presentModalViewController:nav animated:NO];
    
    //[[NSNotificationCenter defaultCenter] postNotificationName:@"regFn" object:nil];
    
    
    
    
    
    
    
    
}

-(void)UserClickOnFastLoginBut:(id)sender{
    
    UIButton * mybut = (UIButton *)sender;
    int curtag = mybut.tag-1000;
    
    for (int i = 0; i<fastLoginButArr.count; i++) {
        UIButton * oneBut = [fastLoginButArr objectAtIndex:i];
        if (i==curtag) {
            [oneBut setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:@"2loginpicbut%i",i]] forState:0];
        }
        else{
            [oneBut setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:@"loginpicbut%i",i]] forState:0];
        }
    }
    
    switch (curtag) {
        case 0:
        {
            //新浪登陆
            //            SinaWeiBoViewController * sinaWeiBo = [[SinaWeiBoViewController alloc] init];
            //            [self.navigationController pushViewController:sinaWeiBo animated:YES];
            //            [sinaWeiBo release];
            
        }
            break;
        case 1:
        {
            //qq登陆
            //            NSArray * _permissions =  [[NSArray arrayWithObjects:
            //                                        @"get_user_info",@"add_share", @"add_topic",@"add_one_blog", @"list_album",
            //                                        @"upload_pic",@"list_photo", @"add_album", @"check_page_fans",nil] retain];
            //            _tencentOAuth = [[TencentOAuth alloc] initWithAppId:@"218315"
            //                                                    andDelegate:self];
            //            _tencentOAuth.redirectURI = @"www.qq.com";
            //            [_tencentOAuth authorize:_permissions inSafari:NO];
            
        }
            break;
        case 2:
        {
            //开心网登陆
        }
            break;
        case 3:
        {
            //人人网登陆
        }
            break;
            
            
        default:
            break;
    }
    
}



#pragma mark - uitextfield协议处理

- (void)textFieldDidEndEditing:(UITextField *)textField{
    
    [textField resignFirstResponder];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    [textField resignFirstResponder];
    return YES;
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
